package org.example.zuoye.api;

import jakarta.servlet.http.HttpSession;
import org.example.zuoye.entity.Account;
import org.example.zuoye.entity.Admin;
import org.example.zuoye.entity.Result;
import org.example.zuoye.service.AdminService;
import org.example.zuoye.util.JwtUtils;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/08/13/ 9:31
 * @Description
 */
@RestController
@RequestMapping("/api/v1/admin")
public class UserApi {
    // 单例模式，对数据进行加密
    private static final PasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
    @Autowired
    private AdminService adminService;

    @Value("${jwt.secret.key}")
    private String jwtSecretKey;

    @PostMapping("/login")
    public Result login(@RequestBody Account account, HttpSession session){
        if(!StringUtils.hasText(account.getCaptcha())){
            return Result.error("验证码不能为空");
        }
        if (account == null || account.getUsername() == null || account.getPassword() == null){
            return Result.error("用户名或密码不能为空");
        }
        String answer = (String) session.getAttribute("captcha");
        // 验证码校验
        if (!answer.equalsIgnoreCase(account.getCaptcha())){
            return Result.error("验证码错误");
        }
        //登录的认证
        Admin admin = this.adminService.findByUsername(account.getUsername());

        if (admin == null){
            return Result.error("用户名错误");
        }
        // 密码校验:进行数据库的解密和界面操作
        System.out.println("admin.getPassword() = " + admin.getPassword());
        System.out.println("account.getPassword() = " + account.getPassword());
        System.out.println("passwordEncryptor.checkPassword(account.getPassword(), admin.getPassword()) = " + passwordEncryptor.checkPassword(account.getPassword(), admin.getPassword()));

        if (!passwordEncryptor.checkPassword(account.getPassword(), admin.getPassword())){
            return Result.error("密码错误");
        }


        // 颁发令牌
        Map<String, Object> data = Map.of("username", account.getUsername());
        String jwt = JwtUtils.encode(account.getUsername(), data, jwtSecretKey);


        return Result.success("登录成功",jwt);
    }



}
